package main

import (
	"bufio"
	"flag"
	"os"
	"strings"

	"gitee.com/dark.H/dark"
	"gitee.com/dark.H/darknet"
	"gitee.com/dark.H/darknet/clip"
	"gitee.com/dark.H/darknet/console"
	"gitee.com/dark.H/darknet/tcp"
	"github.com/nsf/termbox-go"
)

func main() {
	usessh := false
	payload := ""
	proxy := ""
	flag.BoolVar(&usessh, "ssh", false, "true to use ssh from clipboard {'host':xxx ,'pwd':'xxx'}")
	flag.StringVar(&payload, "pay", "", "payload file from bp ")
	flag.StringVar(&proxy, "proxy", "", "payload file from bp ")

	flag.Parse()

	if usessh {
		e := clip.Read()
		je := e.Json()
		if host, ok := je["host"]; ok {
			if pwd, ok2 := je["pwd"]; ok2 {
				if pr, ok3 := je["proxy"]; ok3 {
					s := tcp.AsSSH(dark.Str(host.(string)), dark.Str(pwd.(string)), dark.Str(pr.(string)))
					// s.Onkey = func(line string) {
					// 	fmt.Println("on line:", line)
					// }
					if s != nil {
						s.Terminal()
					}

				} else {
					s := tcp.AsSSH(dark.Str(host.(string)), dark.Str(pwd.(string)))
					s.Onkey = func(line string) {
						// dark.Str(line).ToFile("/tmp/test.log")
						if strings.TrimSpace(line) == "test" {
							e := console.Select(dark.List[string]{"sdf", "asdfasdf", "asdfasdg"})
							dark.Str(e).ToFile("/tmp/test2.log")
						}
					}
					if s != nil {
						s.Terminal()
					}

				}
			}
		}
		return
	}

	if len(os.Args) == 1 {
		buff := bufio.NewScanner(os.Stdin)
		buff.Split(bufio.ScanLines)
		text := dark.Str("")
		for buff.Scan() {
			text += dark.Str(buff.Text() + "\n")
		}

		t := console.NewTextPanel(text, &console.PanelLoc{
			X: 1,
			Y: 1,
		})
		t.OnKeyExtention('c', func(t *console.TextPanel) {
			word := t.GetSelect()
			clip.Write(word)
			t.Label = dark.Str("Copy to clip: :%s ").F(word.Color("B", "g"))
		})
		console.AppStart(t)

		if t.After != nil {
			termbox.Init()
			t.After()
		}
		t.GetSelect().Println()

	} else {
		if payload != "" {
			pays := dark.List[string](flag.Args()).Join(" ")
			kv := dark.Dict[dark.Str]{}
			pays.Split(",").Every(func(no int, i dark.Str) {
				kv = kv.Update(i.ParseKV())
			})

			if dark.Str(payload).IsExists() {
				buf := dark.Str(payload).MustAsFile()

				req := darknet.AsReq(buf.FormatDict(kv).AsNetReq())
				if proxy != "" {
					req.Proxy = dark.Str(proxy)
				}
				req.Str.Color("B", "g").Add("\n\n").Print()

				req.Go().Print()
			} else {
				if dark.Str(payload).StartsWith("http") {
					buf := dark.Str(payload)
					req := darknet.AsReq(buf.FormatDict(kv).AsNetReq())
					if proxy != "" {
						req.Proxy = dark.Str(proxy)
					}
					req.Str.Color("B", "g").Add("\n\n").Print()
					req.Go().Print()
				} else {
					dark.Str("at least set some payload").Println()
				}

			}
		}
	}

}
